<template>
  <div>
    <el-upload
      action="#"
      :limit="1"
      list-type="picture-card"
      :file-list="fileList"
      :on-remove="remove"
      :on-preview="preview"
      :on-change="change"
      :before-upload="beforeAvatarUpload"
      :http-request="onload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <!-- 上传进度 -->
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width: 180px"
    />
    <!-- 图片预览弹层 -->
    <el-dialog
      title="图片预览"
      :visible="dialogShow"
      width="30%"
      :before-close="close"
    >
      <img :src="img" style="width: 100%" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKID84kAJCoEOK0QZT6RYP0KN9esqXy82f17',
  SecretKey: 'qQjlW0DAqELBk23mFSYOxFG0TfcJjtmO'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      fileList: [],
      img: '',
      dialogShow: false,
      uid: null,
      percent: 0,
      showPercent: false
    }
  },
  methods: {
    // 文件上传检查
    beforeAvatarUpload(file) {
      if (file.size > 1024 * 1024 * 5) {
        return this.$message('图片大小不超过5M')
      }
      const type = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg']
      if (!type.some((item) => item === file.type)) {
        return this.$message('图片格式png, jpg, jpeg, gif')
      }
    },
    change(file, fileList) {
      this.fileList = fileList
    },
    // 删除图片
    remove(file, fileList) {
      this.fileList = fileList
    },
    // 图片预览
    preview(file) {
      this.dialogShow = true
      this.img = file.url
    },
    close() {
      this.dialogShow = false
    },
    // 自定义文件上传
    onload({ file }) {
      this.showPercent = true
      cos.putObject(
        {
          Bucket: 'imgsrc-1309929131' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD',
          Body: file, // 上传文件对象
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        },
        (err, data) => {
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map((item) => {
              return { url: 'http://' + data.Location, upload: true } // upload=true代表完全上传成功
            })
          }
          this.showPercent = false
        }
      )
    }
  }
}
</script>

<style scoped lang="scss"></style>
